<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="类别名称">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading"
                                      @search="handleSearch" v-model="pageData.dropDownData" :filter-option="false"
                                      allow-search allow-clear @focus="focusSel">
                                <a-option v-for="item in pageData.nameList1" :value="item">{{ item }}</a-option>
                            </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.dropDownData"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar
            :items="pageData.btnList"
            @add="addHandler"
            @import="importHandler"
            @del="deleteHandler"
            @select="selectHandler"
            @export="exports"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <!-- <a-tabs   :justify="true">
                    <a-tab-pane title="字典明细管理"> -->
      <!-- <a-table size="mini" style="height:100%"  :scrollbar="scrollbar" sticky-header @page-change="pagination.change" stripe
                                 :bordered="true" :columns="tableColumns" @change="handleChange"  :draggable="{type:'handle',width:20,fixed:true}"
                                 :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                                 v-model:selected-keys="selectedRowKeys" :loading="pageData.pageLoading" :data="table.dataList"
                                 :pagination="false"
                                 :rowKey="rowKey" :scroll="{x:'100%',y:'100%' ,maxHeight:'100%'}">
                            <template #obsoleteState="{ record }">
                                <a-space size="large">
                                    <a-switch checked-color="#F53F3F" unchecked-color="#14C9C9"
                                              v-model="record.obsoleteState" :checked-value="1" :unchecked-value="0"
                                              disabled>
                                        <template #checked>
                                            停用
                                        </template>
                                        <template #unchecked>
                                            启用
                                        </template>
                                    </a-switch>
                                </a-space>
                            </template>
                            <template #action="{ record }">
                                <a-button type="primary" size="small" status="warning" @click="editHandler(record)"
                                          v-if="pageData.isEdit">
                                    <template #icon>
                                        <icon-edit/>
                                    </template>
                                    修 改
                                </a-button>
                            </template>
                        </a-table> -->
      <!-- <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :localeText="localeText1"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 100%"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
      >
      </AgGridVuesCopys> -->
      <div class="w-full h-full">
        <encapsulation-agrid
          style="height: 100%"
          ref="gridOption"
          :configaggrid="configTable"
        ></encapsulation-agrid>
      </div>
      <!-- </a-tab-pane>
                </a-tabs> -->
    </template>
    <!-- <paginationCopys
      :total="pagination.total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      :page-size="pagination.pageSize"
      :current="pagination.page"
      style="justify-content: center"
      :page-size-options="pagingList1"
    /> -->
    <a-drawer
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :width="400"
      :mask-closable="false"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
      :ok-loading="pageData.pageLoading"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="140px"
            label="编号"
            field="detailCode"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '类别编号必填' }]"
          >
            <a-input
              :class="{ bacClass: !dataForm.sysType == 0 }"
              placeholder=""
              v-model="dataForm.detailCode"
            />
          </a-form-item>
          <a-form-item
            label-col-flex="140px"
            label="类别名称"
            field="codeType"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '类别名称必填' }]"
          >
            <a-select
              popup-container="html"
              :class="{ bacClass: !dataForm.sysType == 0 }"
              placeholder=""
              v-model="dataForm.codeType"
              :disabled="dataForm.sysType == 0"
              allow-clear
              allow-search
            >
              <a-option v-for="item in pageData.nameList" :value="item['codeType']"
                >{{ item['typeName'] }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label-col-flex="140px"
            label="词典明细名称"
            field="detailName"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '词典明细名称必填' }]"
          >
            <a-input
              :class="{ bacClass: !dataForm.sysType == 0 }"
              placeholder=""
              v-model="dataForm.detailName"
              :disabled="dataForm.sysType == 0"
            />
          </a-form-item>
          <a-form-item
            label-col-flex="140px"
            label="词典明细英文名称"
            field="detailNameEn"
            :rules="[{ validator: isEng }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input
              :class="{ bacClass: !dataForm.sysType == 0 }"
              v-model="dataForm.detailNameEn"
              :disabled="dataForm.sysType == 0"
            />
          </a-form-item>
          <a-form-item label-col-flex="140px" label="是否停用" field="obsoleteState">
            <a-switch
              checked-color="#F53F3F"
              unchecked-color="#14C9C9"
              v-model="dataForm.obsoleteState"
              :checked-value="1"
              :unchecked-value="0"
              style="width: 65px"
            >
              <template #checked> 停用 </template>
              <template #unchecked> 启用 </template>
            </a-switch>
          </a-form-item>
          <a-form-item label-col-flex="140px" label="备注" field="remark">
            <a-textarea
              class="bacClass"
              placeholder=""
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'

  import { ref, reactive, onMounted, onActivated } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import emitter from '@/hooks/useEventBus'
  import validate from '@/hooks/useValidate'
  import { DatasetComponent } from 'echarts/components'
  import { AnyARecord } from 'dns'
  import usePermission from '@/store/modules/permission'
  
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'

  interface ClothInfo {
    id: number | string | null
    codeType: any
    detailName: string
    detailNameEn: string
    remark: string
    typeName: string
    sysType: any
    obsoleteState: any
    deteleState: string | undefined | null
    createName: string | undefined | null
    createTime: string | undefined | null
    updateName: string | undefined | null
    updateTime: string | undefined | null
    detailCode: any
  }

  export default {
    name: 'DictionaryDetails',
    setup() {
      function PageSize(val: any) {
        pagination.page = val
        doRefresh()
      }

      function change1(val: any) {
        pagination.pageSize = val
        doRefresh()
      }
      //查询
      function doRefresh() {
        // pageData.pageLoading = true
        // post({
        //   url: 'dict/dictTypeDetail/getPage',
        //   data: {
        //     page: pagination.page,
        //     size: pagination.pageSize,
        //     deleteState: 0,
        //     typeName: pageData.dropDownData,
        //   },
        // })
        //   .then(({ data, code }: any) => {
        //     if (code === 200) {
        //       data.list = data.list.map(function (o: any) {
        //         o['disabled'] = o['sysType'] == 0 ? true : false
        //         return o
        //       })
        //       gridOption.value.setRowData(data.list)
        //       table.handleSuccess(data.list)
        //       pagination.setTotalSize(data.total)
        //     }
        //   })
        //   .catch(console.log)
        //   .finally(() => {
        //     pageData.pageLoading = false
        //   })
        try {
          gridOption.value.setQuery({
            deleteState: 0,
            typeName: pageData.dropDownData,
          })
        } catch (error) {
          console.log(error)
        }
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const tableColumns = useTableColumn([
        {
          title: '类别名称',
          key: 'typeName',
          dataIndex: 'typeName',
          width: 150,
        },
        {
          title: '编号',
          key: 'detailCode',
          dataIndex: 'detailCode',
          width: 150,
        },
        {
          title: '词典明细名称',
          key: 'detailName',
          dataIndex: 'detailName',
          width: 150,
        },
        {
          title: '词典明细英文名',
          key: 'detailNameEn',
          dataIndex: 'detailNameEn',
          width: 150,
        },

        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '是否停用',
          key: 'obsoleteState',
          dataIndex: 'obsoleteState',
          slotName: 'obsoleteState',
          width: 150,
          fixed: 'right',
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '操作',
          key: 'id',
          dataIndex: 'id',
          slotName: 'action',
          width: 150,
          fixed: 'right',
        },
      ])
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        nameList: []
        dropDownData: any
        pageLoading: boolean
        nameList1: []
        rHeight: any
        btnList: any[]
        isEdit: boolean
        brandTypeList: []
      }>({
        showAdd: false,
        sideTitle: '新增字典明细管理',
        dropDownData: '',
        nameList: [],
        pageLoading: false,
        nameList1: [],
        rHeight: '',
        btnList: [],
        isEdit: false,
        brandTypeList: [],
      })
      //下拉框得到焦点
      const focusSel = () => {
        selCxAll({})
      }
      //下拉数据
      const options = ref<any>(pageData.nameList1)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { key: value }
          loading.value = true
          window.setTimeout(() => {
            selCxAll(ob)
            options.value = pageData.nameList1
            loading.value = false
          }, 200)
        } else {
          options.value = []
        }
      }

      //下拉框查询
      function selCxAll(val: any) {
        post({
          url: 'dict/dictType/getDictTypeNameByKey',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            console.log(data)
            // (data as string[]).splice(0, 0, "全部");
            pageData.nameList1 = data
            console.log(pageData.nameList1)
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      onMounted(() => {
        emitter.on('refresh-DictionaryDetails', () => {
          doRefresh();
          selCxAll({})
        })
        pageData.rHeight = document.getElementById('BaseInfoSetting')?.clientHeight
        //表格的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 200
        }

        window.addEventListener('resize', () => {
          pageData.rHeight = document.getElementById('BaseInfoSetting')?.clientHeight

          //表格的高
          if (pageData.rHeight !== undefined) {
            pageData.rHeight = pageData.rHeight - 200
          }
        })
      })
      //查询
      const selectHandler = () => {
        pagination.page = 1
        doRefresh()
      }

      const addHandler = () => {
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else if (key === 'obsoleteState') {
            dataForm[key] = 0
          } else if (key === 'sysType') {
            dataForm[key] = 1
          } else {
            dataForm[key] = ''
          }
        }
        pageData.showAdd = true
        pageData.sideTitle = '新增字典明细管理'
        dropDownFf()
      }

      //下拉框渲染
      const dropDownFf = () => {
        post({
          url: 'dict/dictType/getDictTypeName',
        }).then(({ data, code, message }: any) => {
          if (code === 200) {
            pageData.nameList = data
          } else {
            Message.error({
              content: message,
              duration: 5000,
            })
          }
        })
      }
      const dataForm = reactive<ClothInfo>({
        id: null,
        codeType: null,
        detailName: '',
        detailNameEn: '',
        remark: '',
        deteleState: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        sysType: 1,
        obsoleteState: 0,
        typeName: '',
        detailCode: '',
      })

      const gridOption = ref()
      // const gridReady = (params: any) => {
      //   gridOption.value = params.api
      // }

      const formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            if (pageData.sideTitle === '新增字典明细管理') {
              const pattern = /^\d+[A-Z]$/
              if (dataForm.codeType == 33) {
                if (!pattern.test(dataForm.detailName)) {
                  Message.warning('要求值格式为“任意数字”+“任意大写字母”')
                  return
                }
              }
              pageData.pageLoading = true
              post({
                url: 'dict/dictTypeDetail/insert',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            } else {
              pageData.pageLoading = true
              post({
                url: 'dict/dictTypeDetail/update',
                data: [dataForm],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false

                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                    doRefresh()
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            }
          }
        })
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows() === 0) {
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              url: 'dict/dictTypeDetail/delete',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '修改失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }

      const editHandler = (record: ClothInfo) => {
        dropDownFf()
        dataForm.id = record.id
        dataForm.typeName = record.typeName
        dataForm.codeType = record.codeType
        dataForm.detailName = record.detailName
        dataForm.detailNameEn = record.detailNameEn
        dataForm.remark = record.remark
        dataForm.sysType = record.sysType
        dataForm.obsoleteState = record.obsoleteState
        dataForm.detailCode = record.detailCode
        pageData.sideTitle = '修改字典明细管理'
        pageData.showAdd = true
      }
      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      //input离开焦点 将小写转大写
      const inputBlur = () => {
        dataForm.codeType = dataForm.codeType.toUpperCase()
      }
      //导出
      const exports = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        } else {
          let idList: any = []
          gridOption.value.getSelectedRows().forEach(function (o: any) {
            idList.push(o['id'])
          })
          //将表头拼接出来
          let head =
            '<th>类别名称</th><th>明细名称</th><th>英文名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th><th>是否停用</th>'
          //拿到当前表格数据与勾选的行做筛选
          const tableDataList = gridOption.value.getListData()
          let nowRow = tableDataList.dataList.filter(function (o) {
            return (
              gridOption.value
                .getSelectedRows()
                .map((o: any) => {
                  return o.id
                })
                .indexOf(o['id']) !== -1
            )
          })
          let body = ''
          nowRow.forEach(function (o) {
            body += '<tr><td>' + o['typeName'] + '</td>'
            body += '<td>' + o['detailName'] + '</td>'
            body += '<td>' + o['detailNameEn'] + '</td>'
            body += '<td>' + o['remark'] + '</td>'
            body += '<td>' + o['createName'] + '</td>'
            body += '<td>' + o['createTime'] + '</td>'
            body += '<td>' + o['updateName'] + '</td>'
            body += '<td>' + o['updateTime'] + '</td>'
            body += '<td>' + (o['obsoleteState'] === 0 ? '是' : '否') + '</td>'
            body += '</tr>'
          })
          tableToXlsx(head, '字典明细管理', body)
          console.log(table)
        }
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }

      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', () => {
          console.log(this)
        })
      }
      //判断只能写英文
      const isEng = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          var isletter = /^[a-zA-Z]+$/.test(value)
          if (!isletter) {
            cb('填写的值只能是英文！')
          }
          resolve()
        })
      }
      const headerShow = ref<boolean>(true)
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

      if (permissionStore.hasPermisson('zdmxgl.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('zdmxgl.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('zdmxgl.sc')) {
        pageData.btnList.push('删除')
      }
      if (permissionStore.hasPermisson('zdmxgl.dc')) {
        pageData.btnList.push('导出')
      }
      // if (permissionStore.hasPermisson('zdmxgl.dr')) {
      //     pageData.btnList.push("导入")
      // }
      if (permissionStore.hasPermisson('zdmxgl.xg')) {
        pageData.isEdit = true
      }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      let tc: any[] = tableColumns.map((o: any) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        if (o.slotName === 'action') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 80
          obj['cellRenderer'] = {
            template: `<el-button style="color:#165dff;" link @click="a" v-if="f">修改</el-button>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              let f = permissionStore.hasPermisson('zdmxgl.xg')
              return {
                a,
                f,
              }
            },
          }
        }
        if (o.slotName === 'obsoleteState') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 100
          obj['cellRenderer'] = {
            template: `
                    <a-space>
                <el-tag type="info" v-if="a">停用</el-tag>
                <el-tag type="success" v-if="!a">启用</el-tag>
                </a-space>`,
            setup(props: any) {
              const a = ref()
              if (props.params.data.obsoleteState == '1') {
                a.value = true
              } else {
                a.value = false
              }
              return {
                a,
              }
            },
          }
        }

        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      let configTable = ref({
        url: 'dict/dictTypeDetail/getPage', //接口路径
        queryData: {
          //接口参数
        },
        // isGet:true,//是否是get请求
        // isLimit:true,//后端分页接收limit而非size
        paginationShow: true, //分页是否显示
        invokeiIterface: true, //是否调用接
        rowMultiSelectWithClick: true, //点击行是否多选
        column: tc,
        fileName: 'DictTypeDetail', //导出文件名
      })
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      const localeText1: any = ref(localeText)
      const huiche = () => {
        doRefresh()
      }
      const pagingList1: any = ref(pagingList)
      return {
        huiche,
        pagingList1,
        localeText1,
        defaultColDef,
        tc,
        headerShow,
        importHandler,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        editHandler,
        selectHandler,
        inputBlur,
        isChiese,
        exports,
        isEng,
        options,
        loading,
        handleSearch,
        focusSel,
        PageSize,
        change1,
        handleChange,
        gridOption,
        // gridReady,
        configTable,
      }
    },
    components: { Toolbar,  },
  }
</script>
<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
</style>
